package com.example.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.auth.domain.DataNode;
import com.example.config.exception.GlobalExcetion;
import com.example.config.redis.CacheService;
import com.example.feign.NodeFeignService;
import com.example.feign.SysTableScriptFeignService;
import com.example.system.domain.BusSystemTable;
import com.example.system.domain.SysTableScript;
import com.example.system.mapper.BusSystemTableMapper;
import com.example.system.service.BusSystemTableService;
import com.example.util.sql.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
* @author CETC
* @description 针对表【bus_system_table】的数据库操作Service实现
* @createDate 2025-10-25 10:21:48
*/
@Service
public class BusSystemTableServiceImpl extends ServiceImpl<BusSystemTableMapper, BusSystemTable>
    implements BusSystemTableService{

    @Autowired
    private CacheService cacheService;

    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    private NodeFeignService nodeFeignService;

    @Autowired
    private SysTableScriptFeignService sysTableScriptFeignService;


    @Override
    public void createBusSystemTable(String tableScripeId) throws GlobalExcetion {
        SysTableScript sysTableScript=sysTableScriptFeignService.getSysTableScriptById(tableScripeId);
        if(sysTableScript!=null){
            createBusSystemTable(sysTableScript);
        }
    }

    @Override
    public void createBusSystemTable(SysTableScript sysTableScript) throws GlobalExcetion {
        String tableName=sysTableScript.getTableName();
        List<String> tableNames=new ArrayList<String>();
        for (int i = 1; i <= sysTableScript.getCreateNum(); i++) {
            tableNames.add(tableName+"_"+i);
        }
        DataNode dataNode =nodeFeignService.getDataNodeConfigByServerName(this.appName);
        if(dataNode ==null){
            throw new GlobalExcetion(1,"数据节点异常");
        }
        for (int i = 0; i < tableNames.size(); i++) {
           boolean isExist=this.tableExist(tableNames.get(i));
           if(!isExist){
               System.out.println(tableNames.get(i)+" 不存在");
               String sql=sysTableScript.getTableScript();
               sql=sql.replaceFirst(sysTableScript.getTableName(),tableNames.get(i));
               createTable(sql);
               Integer index=i+1;
               String tableno=sysTableScript.getTableNo()+"_"+index;
               String tablenode=tableNames.get(i);
               BusSystemTable busSystemTable=this.getBusSystemTable(tableno,tablenode);
               if(busSystemTable==null){
                   busSystemTable=new BusSystemTable();
                   busSystemTable.setTableNo(tableno);
                   busSystemTable.setTableNode(tablenode);
                   busSystemTable.setMaxNum(500); //最大用户数
                   busSystemTable.setUserNum(0);
                   busSystemTable.setIsDeleted(0);
                   busSystemTable.setTableName(sysTableScript.getTableName());
                   busSystemTable.setDsNo(dataNode.getId());
                   this.baseMapper.insert(busSystemTable);
               }
           }
        }
    }

    @Override
    public void createTable(String sqlScript) {
        try {
            super.baseMapper.executeSql(sqlScript);
            System.out.println("表创建成功");
        } catch (Exception e) {
            System.out.println("表创建失败: " + e.getMessage());
        }
    }

    @Override
    public void executeSql(String sqlScript) {
        System.out.println("执行sql: " + sqlScript);
        super.baseMapper.executeSql(sqlScript);
    }

    @Override
    public boolean tableExist(String tableName) {
        return super.baseMapper.existsTableMySQL(tableName) > 0;
    }

    @Override
    public BusSystemTable getBusSystemTable(String no, String node) {
        LambdaQueryWrapper<BusSystemTable> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BusSystemTable::getTableNo,no);
        lambdaQueryWrapper.eq(BusSystemTable::getTableNode,node);
        return this.getOne(lambdaQueryWrapper);
    }

    @Override
    public List<BusSystemTable> getListByTableName(String tableName) {
        LambdaQueryWrapper<BusSystemTable> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BusSystemTable::getTableName,tableName);
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public List<String> getTableList(SysTableScript sysTableScript) {
        List<String> tableNames=new ArrayList<String>();
        for (int i = 1; i <= sysTableScript.getCreateNum(); i++) {
            String tableName=sysTableScript.getTableName();
            tableNames.add(tableName+"_"+i);
        }
        return tableNames;
    }

    @Override
    public String createUUID(String tableName) {
        BusSystemTable busSystemTable=this.getByRealTableName(tableName);
        if(busSystemTable!=null){
            return busSystemTable.getTableNo()+"#"+ IdUtils.getUUID();
        }
        return "";
    }

    @Override
    public String getTableNameByUUID(String uuid) throws GlobalExcetion {
        String[] arr=uuid.split("#");
        if(arr.length<2){
            throw new GlobalExcetion(1,"非法uuid");
        }
        if(!StringUtils.hasText(arr[0])){
            throw new GlobalExcetion(1,"非法uuid");
        }
        String tableNo=arr[0];
        BusSystemTable table=this.getByTableNo(tableNo);
        return table.getTableNode();
    }

    @Override
    public BusSystemTable getByRealTableName(String realTableName) {
        if(cacheService.containsKey(this.appName+"getByRealTableName",realTableName)){
            return cacheService.get(this.appName+"getByRealTableName",realTableName,BusSystemTable.class);
        }else {
            LambdaQueryWrapper<BusSystemTable> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BusSystemTable::getTableNode,realTableName);
            BusSystemTable busSystemTable=this.getOne(lambdaQueryWrapper);
            cacheService.put(this.appName+"getByRealTableName",realTableName,busSystemTable);
            return busSystemTable;
        }
    }

    @Override
    public BusSystemTable getByTableNo(String tableNo) {
        if(cacheService.containsKey(this.appName+"getByTableNo",tableNo)){
            return cacheService.get(this.appName+"getByTableNo",tableNo,BusSystemTable.class);
        }else {
            LambdaQueryWrapper<BusSystemTable> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BusSystemTable::getTableNo,tableNo);
            BusSystemTable busSystemTable=this.getOne(lambdaQueryWrapper);
            cacheService.put(this.appName+"getByTableNo",tableNo,busSystemTable);
            return busSystemTable;
        }
    }
}




